<?php

function wg_tpl_form_field_district($name, $values = array())
{
    $html = '';
    if (!defined('TPL_INIT_DISTRICT')) {
        $html .= '
		<script type="text/javascript">
			require(["district"], function(dis){
				$(".tpl-district-container").each(function(){
					var elms = {};
					elms.province = $(this).find(".tpl-province")[0];
					elms.city = $(this).find(".tpl-city")[0];
					elms.district = $(this).find(".tpl-district")[0];
					var vals = {};
					vals.province = $(elms.province).attr("data-value");
					vals.city = $(elms.city).attr("data-value");
					vals.district = $(elms.district).attr("data-value");
					dis.render(elms, vals, {withTitle: true});
				});
			});
		</script>';
        define('TPL_INIT_DISTRICT', true);
    }
    if (empty($values) || !is_array($values)) {
        $values = array('province' => '', 'city' => '', 'district' => '');
    }
    if (empty($values['province'])) {
        $values['province'] = '';
    }
    if (empty($values['city'])) {
        $values['city'] = '';
    }
    if (empty($values['district'])) {
        $values['district'] = '';
    }
    $html .= '
		<div class="row row-fix tpl-district-container">
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select  lay-ignore name="' . $name . '[province]" data-value="' . $values['province'] . '" class="form-control tpl-province">
				</select>
			</div>
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select  lay-ignore name="' . $name . '[city]" data-value="' . $values['city'] . '" class="form-control tpl-city">
				</select>
			</div>
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select  lay-ignore name="' . $name . '[district]" data-value="' . $values['district'] . '" class="form-control tpl-district">
				</select>
			</div>
		</div>';
    return $html;
}


function wg_tpl_form_field_city($name, $values = array())
{
    $html = '';
    if (!defined('TPL_INIT_DISTRICT')) {
        $html .= '
		<script type="text/javascript">
			require(["district"], function(dis){
				$(".tpl-district-container").each(function(){
					var elms = {};
					elms.province = $(this).find(".tpl-province")[0];
					elms.city = $(this).find(".tpl-city")[0];
					var vals = {};
					vals.province = $(elms.province).attr("data-value");
					vals.city = $(elms.city).attr("data-value");
					dis.render(elms, vals, {withTitle: true});
				});
			});
		</script>';
        define('TPL_INIT_DISTRICT', true);
    }
    if (empty($values) || !is_array($values)) {
        $values = array('province' => '', 'city' => '');
    }
    if (empty($values['province'])) {
        $values['province'] = '';
    }
    if (empty($values['city'])) {
        $values['city'] = '';
    }
    $html .= '
		<div class="row row-fix tpl-district-container">
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select  lay-ignore name="' . $name . '[province]" data-value="' . $values['province'] . '" class="form-control tpl-province">
				</select>
			</div>
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select  lay-ignore name="' . $name . '[city]" data-value="' . $values['city'] . '" class="form-control tpl-city">
				</select>
			</div>
		</div>';
    return $html;
}

function wg_tpl_form_field_image($name, $value = '', $default = '', $options = array())
{
    if (empty($default)) {
        $default = '/static/img/nopic.jpg';
    }
    $val = asset($default);
    if (!empty($value)) {
        $val = ($value);
    }
    if (defined('SYSTEM_WELCOME_MODULE')) {
        $options['uniacid'] = 0;
    }
    if (empty($options['class_extra'])) {
        $options['class_extra'] = '';
    }
    if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
        if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
            exit('图片上传目录错误,只能指定最多两级目录,如: "we7_store","we7_store/d1"');
        }
    }
    $options['direct'] = true;
    $options['multiple'] = false;
    if (isset($options['thumb'])) {
        $options['thumb'] = !empty($options['thumb']);
    }
    $options['fileSizeLimit'] = intval($GLOBALS['_W']['setting']['upload']['image']['limit']) * 1024;
    $s = '';
    if (!defined('TPL_INIT_IMAGE')) {
        $s = '
		<script type="text/javascript">
		    layui.use("upload", function(){
                var upload = layui.upload;
               
                //执行实例
                var uploadInst = upload.render({
                    elem: "#upload" //绑定元素
                    ,url: "'.route('common.uploadImage').'" //上传接口
                    ,field:"image"
                    ,done: function(res){
                        var btn = $("#upload");
                        var ipt = btn.parent().prev();
				        var img = ipt.parent().next().children();  
				        if(img.length > 0){
							img.get(0).src = res.data.url;
						}
				        ipt.val(res.data.url);
						ipt.attr("url",res.data.url);
                    }
                    ,error: function(){
                      //请求异常回调
                    }
                });
            });
			function deleteImage(elm){
				$(elm).prev().attr("src", "/static/img/nopic.jpg");
				$(elm).parent().prev().find("input").val("");
			}
		</script>';
        define('TPL_INIT_IMAGE', true);
    }

    $s .= '
		<div class="input-group ' . $options['class_extra'] . '">
            <input type="text" name="' . $name . '" value="' . $value . '"' . ($options['extras']['text'] ? $options['extras']['text'] : '') . ' class="form-control" autocomplete="off">
            <span class="input-group-btn" style="margin-left: 5px">
				<button type="button" class="layui-btn" id="upload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
			</span>
		</div>
		<div class="input-group' . $options['class_extra'] . '" style="margin-top:.5em;    width:auto;display:table;border-collapse: separate;">
			<img src="' . $val . '" onerror="this.src=\'' . $default . '\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail" ' . ($options['extras']['image'] ? $options['extras']['image'] : '') . ' width="150" />
			<em class="close" style="position:absolute; top: 0px; right: -14px;" title="删除这张图片" onclick="deleteImage(this)">×</em>
		</div>';
    return $s;
}


function wg_tpl_form_field_multi_image($name, $value = array(), $options = array())
{
    global $_W;
    $options['multiple'] = true;
    $options['direct'] = false;
    $options['fileSizeLimit'] = intval($GLOBALS['_W']['setting']['upload']['image']['limit']) * 1024;
    if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
        if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
            exit('图片上传目录错误,只能指定最多两级目录,如: "we7_store","we7_store/d1"');
        }
    }
    $s = '';
    if (!defined('TPL_INIT_MULTI_IMAGE')) {
        $s = '
<script type="text/javascript">
	function uploadMultiImage(elm) {
		var name = $(elm).next().val();
		util.image( "", function(urls){
			$.each(urls, function(idx, url){
				$(elm).parent().parent().next().append(\'<div class="multi-item"><img onerror="this.src=\\\'/web/resource/images/nopic.jpg\\\'; this.title=\\\'图片未找到.\\\'" src="\'+url.url+\'" class="img-responsive img-thumbnail"><input type="hidden" name="\'+name+\'[]" value="\'+url.attachment+\'"><em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em></div>\');
			});
		}, ' . json_encode($options) . ');
	}
	function deleteMultiImage(elm){
		$(elm).parent().remove();
	}
</script>';
        define('TPL_INIT_MULTI_IMAGE', true);
    }

    $s .= <<<EOF
<div class="input-group">
	<input type="text" class="form-control" readonly="readonly" value="" placeholder="批量上传图片" autocomplete="off">
	<span class="input-group-btn">
		<button class="btn btn-default" type="button" onclick="uploadMultiImage(this);">选择图片</button>
		<input type="hidden" value="{$name}" />
	</span>
</div>
<div class="input-group multi-img-details">
EOF;
    if (is_array($value) && count($value) > 0) {
        foreach ($value as $row) {
            $s .= '
<div class="multi-item">
	<img src="' . wgTomedia($row) . '" onerror="this.src=\'/web/resource/images/nopic.jpg\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail">
	<input type="hidden" name="' . $name . '[]" value="' . $row . '" >
	<em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em>
</div>';
        }
    }
    $s .= '</div>';

    return $s;
}

function wg_tpl_form_field_video($name, $value = '', $options = array())
{
    if (!is_array($options)) {
        $options = array();
    }
    if (!is_array($options)) {
        $options = array();
    }
    $options['direct'] = true;
    $options['multi'] = false;
    $options['type'] = 'video';
    $options['fileSizeLimit'] = intval($GLOBALS['_W']['setting']['upload']['audio']['limit']) * 1024;
    $s = '';
    if (!defined('TPL_INIT_VIDEO')) {
        $s = '
<script type="text/javascript">
	function showVideoDialog(elm, options) {
		require(["util"], function(util){
			var btn = $(elm);
			var ipt = btn.parent().prev();
			var val = ipt.val();
			util.audio(val, function(url){
				if(url && url.attachment && url.url){
					btn.prev().show();
					ipt.val(url.attachment);
					ipt.attr("filename",url.filename);
					ipt.attr("url",url.url);
				}
				if(url && url.media_id){
					ipt.val(url.media_id);
				}
			}, ' . json_encode($options) . ');
		});
	}

</script>';
        echo $s;
        define('TPL_INIT_VIDEO', true);
    }

    $s .= '
	<div class="input-group">
		<input type="text" value="' . $value . '" name="' . $name . '" class="form-control" autocomplete="off" ' . ($options['extras']['text'] ? $options['extras']['text'] : '') . '>
		<span class="input-group-btn">
			<button class="btn btn-default" type="button" onclick="showVideoDialog(this,' . str_replace('"', '\'', json_encode($options)) . ');">选择媒体文件</button>
		</span>
	</div>';
    return $s;
}

if (!function_exists('wg_tpl_form_field_position')) {
    /**
     * 地理位置
     * @param $field
     * @param array $value
     * @return string
     */
    function wg_tpl_form_field_position($field, $value = array())
    {
        global $_W;
        $s = '';

        if (!defined('TPL_INIT_COORDINATE')) {
            $s .= '<script type="text/javascript">
                    myrequire.path = "' . $_W['siteroot'] . 'addons/ewei_shopv2/static/js/myrequire/";
                    myrequire(["init"]);
                    function showCoordinate(elm) {
                            var val = {};
                            val.lng = parseFloat($(elm).parent().prev().prev().find(":text").val());
                            val.lat = parseFloat($(elm).parent().prev().find(":text").val());
                            val = biz.BdMapToTxMap(val.lat,val.lng);
                            biz.map(val, function(r){
                                var address_label = $("#address_label");
                                if (address_label.length>0)
                                {
                                    address_label.val(r.label);
                                }
                                r = biz.TxMapToBdMap(r.lat,r.lng);
                                $(elm).parent().prev().prev().find(":text").val(r.lng);
                                $(elm).parent().prev().find(":text").val(r.lat);
                            },"' . wgRoute('liveutilsform.map') . '");
                    }
    
                </script>';
            define('TPL_INIT_COORDINATE', true);
        }

        $s .= '
<style>
.modal-body{
    padding: 0px !important;
}
</style>
            <div class="row row-fix">
                <div class="col-xs-4 col-sm-4">
                    <input type="text" name="' . $field . '[lng]" value="' . $value['lng'] . '" placeholder="地理经度"  class="form-control" />
                </div>
                <div class="col-xs-4 col-sm-4">
                    <input type="text" name="' . $field . '[lat]" value="' . $value['lat'] . '" placeholder="地理纬度"  class="form-control" />
                </div>
                <div class="col-xs-4 col-sm-4">
                    <button onclick="showCoordinate(this);" class="btn btn-default" type="button">选择坐标</button>
                </div>
            </div>';
        return $s;
    }
}

if (!function_exists('wg_tpl_form_field_position_merch')) {
    /**
     * 地理位置
     * @param $field
     * @param array $value
     * @return string
     */
    function wg_tpl_form_field_position_merch($field, $value = array())
    {
        global $_W;
        $s = '';

        if (!defined('TPL_INIT_COORDINATE')) {
            $s .= '<script type="text/javascript">
                    myrequire.path = "' . $_W['siteroot'] . 'addons/ewei_shopv2/static/js/myrequire/";
                    myrequire(["init"]);
                    function showCoordinate(elm) {
                            var val = {};
                            val.lng = parseFloat($(elm).parent().prev().prev().find(":text").val());
                            val.lat = parseFloat($(elm).parent().prev().find(":text").val());
                            val = biz.BdMapToTxMap(val.lat,val.lng);
                            biz.map(val, function(r){
                                var address_label = $("#address_label");
                                if (address_label.length>0)
                                {
                                    address_label.val(r.label);
                                }
                                r = biz.TxMapToBdMap(r.lat,r.lng);
                                $(elm).parent().prev().prev().find(":text").val(r.lng);
                                $(elm).parent().prev().find(":text").val(r.lat);
                            },"' . wgRoute('tomerchutils.form.map') . '");
                    }
    
                </script>';
            define('TPL_INIT_COORDINATE', true);
        }

        $s .= '
<style>
.modal-body{
    padding: 0px !important;
}
</style>
            <div class="row row-fix">
                <div class="col-xs-4 col-sm-4">
                    <input type="text" name="' . $field . '[lng]" value="' . $value['lng'] . '" placeholder="地理经度"  class="form-control" />
                </div>
                <div class="col-xs-4 col-sm-4">
                    <input type="text" name="' . $field . '[lat]" value="' . $value['lat'] . '" placeholder="地理纬度"  class="form-control" />
                </div>
                <div class="col-xs-4 col-sm-4">
                    <button onclick="showCoordinate(this);" class="btn btn-default" type="button">选择坐标</button>
                </div>
            </div>';
        return $s;
    }
}

if (!function_exists('wg_tpl_form_field_position_enjoy')) {
    /**
     * 地理位置
     * @param $field
     * @param array $value
     * @return string
     */
    function wg_tpl_form_field_position_enjoy($field, $value = array())
    {
        global $_W;
        $s = '';

        if (!defined('TPL_INIT_COORDINATE')) {
            $s .= '<script type="text/javascript">
                    myrequire.path = "' . $_W['siteroot'] . 'addons/ewei_shopv2/static/js/myrequire/";
                    myrequire(["init"]);
                    function showCoordinate(elm) {
                            var val = {};
                            val.lng = parseFloat($(elm).parent().prev().prev().find(":text").val());
                            val.lat = parseFloat($(elm).parent().prev().find(":text").val());
                            val = biz.BdMapToTxMap(val.lat,val.lng);
                            biz.map(val, function(r){
                                var address_label = $("#address_label");
                                if (address_label.length>0)
                                {
                                    address_label.val(r.label);
                                }
                                r = biz.TxMapToBdMap(r.lat,r.lng);
                                $(elm).parent().prev().prev().find(":text").val(r.lng);
                                $(elm).parent().prev().find(":text").val(r.lat);
                            },"' . wgRoute('enjoyutils.form.map') . '");
                    }
    
                </script>';
            define('TPL_INIT_COORDINATE', true);
        }

        $s .= '
<style>
.modal-body{
    padding: 0px !important;
}
</style>
            <div class="row row-fix">
                <div class="col-xs-4 col-sm-4">
                    <input type="text" name="' . $field . '[lng]" value="' . $value['lng'] . '" placeholder="地理经度"  class="form-control" />
                </div>
                <div class="col-xs-4 col-sm-4">
                    <input type="text" name="' . $field . '[lat]" value="' . $value['lat'] . '" placeholder="地理纬度"  class="form-control" />
                </div>
                <div class="col-xs-4 col-sm-4">
                    <button onclick="showCoordinate(this);" class="btn btn-default" type="button">选择坐标</button>
                </div>
            </div>';
        return $s;
    }
}


if (!function_exists('wg_tpl_form_field_district')) {
    /**
     * 省市区
     * @param $name
     * @param array $values
     * @return string
     */
    function wg_tpl_form_field_district($name, $values = array())
    {
        $html = '';
        if (!defined('TPL_INIT_DISTRICT')) {
            $html .= '
		<script type="text/javascript">
			require(["district"], function(dis){
				$(".tpl-district-container").each(function(){
					var elms = {};
					elms.province = $(this).find(".tpl-province")[0];
					elms.city = $(this).find(".tpl-city")[0];
					elms.district = $(this).find(".tpl-district")[0];
					var vals = {};
					vals.province = $(elms.province).attr("data-value");
					vals.city = $(elms.city).attr("data-value");
					vals.district = $(elms.district).attr("data-value");
					dis.render(elms, vals, {withTitle: true});
				});
			});
		</script>';
            define('TPL_INIT_DISTRICT', true);
        }
        if (empty($values) || !is_array($values)) {
            $values = array('province' => '', 'city' => '', 'district' => '');
        }
        if (empty($values['province'])) {
            $values['province'] = '';
        }
        if (empty($values['city'])) {
            $values['city'] = '';
        }
        if (empty($values['district'])) {
            $values['district'] = '';
        }
        $html .= '
		<div class="row row-fix tpl-district-container">
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select name="' . $name . '[province]" data-value="' . $values['province'] . '" class="form-control tpl-province">
				</select>
			</div>
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select name="' . $name . '[city]" data-value="' . $values['city'] . '" class="form-control tpl-city">
				</select>
			</div>
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
				<select name="' . $name . '[district]" data-value="' . $values['district'] . '" class="form-control tpl-district">
				</select>
			</div>
		</div>';

        return $html;
    }
}
